package xxl.robotlegs.extensions.mediatormap 
{
	import xxl.robotlegs.extensions.mediatormap.api.IMediatorMap;
	import xxl.robotlegs.extensions.mediatormap.impl.MediatorMap;
	import xxl.robotlegs.extensions.viewmanager.api.IViewManager;
	import xxl.robotlegs.framework.api.IContext;
	import xxl.robotlegs.framework.api.IExtension;
	import xxl.robotlegs.framework.api.IInjector;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class MediatorMapExtension implements IExtension 
	{
		private var _injector:IInjector;
		private var _mediatorMap:MediatorMap;
		private var _viewManager:IViewManager;
		
		public function MediatorMapExtension() 
		{
			
		}
		
		public function toString():String
		{
			return "MediatorMapExtension（简介：提供多对多的MediatorMap）";
		}
		
		private function beforeInitializing():void
		{
			_mediatorMap = _injector.getInstance(IMediatorMap);
			if (_injector.satisfiesDirectly(IViewManager))
			{
				_viewManager = _injector.getInstance(IViewManager);
				_viewManager.addViewHandler(_mediatorMap);
			}
		}
		
		private function beforeDestroying():void
		{
			_mediatorMap.unmediateAll();
			if (_injector.satisfiesDirectly(IViewManager))
			{
				_viewManager = _injector.getInstance(IViewManager);
				_viewManager.removeViewHandler(_mediatorMap);
			}
		}
		
		private function whenDestroying():void
		{
			if (_injector.satisfiesDirectly(IMediatorMap))
			{
				_injector.unmap(IMediatorMap);
			}
		}
		
		/* INTERFACE xxl.robotlegs.framework.api.IExtension */
		
		public function extend(context:IContext):void 
		{
			context.beforeInitializing(beforeInitializing)
				.beforeDestroying(beforeDestroying)
				.whenDestroying(whenDestroying);
			_injector = context.injector;
			_injector.map(IMediatorMap).toSingleton(MediatorMap);
		}
		
	}

}